//
//  WNSpringView.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/4.
//

import UIKit

class WNSpringView: UIView {
    
    static let shared = WNSpringView()
    
    lazy var bgView: UIView = {
        let view = UIView.init(frame: CGRect.zero)
        view.backgroundColor = .white
        view.wn_cornerWithBorder(10)
        return view
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = .wn_font(name: .bold, size: 22)
        label.textColor = .black
        label.textAlignment = .center
        return label
    }()
    
    lazy var descLabel: UILabel = {
        let label = UILabel()
        label.font = .wn_font(name: .bold, size: 16)
        label.textColor = .init(named: "black_222222")
        label.textAlignment = .center
        label.numberOfLines = 0
        return label
    }()
        
    lazy var leftBtn: UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.backgroundColor = .init(named: "white_F3F3F3")
        btn.setTitleColor(.lightGray, for: .normal)
        btn.titleLabel?.font = .wn_font(name: .bold, size: 18)
        btn.rx.tap.bind { [weak self] in
            self?.isRightClosure?(false)
            hidenSpringView()
        }.disposed(by: rx.disposeBag)
        btn.wn_cornerWithBorder(18)
        return btn
    }()
    
    lazy var rightBtn: UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.backgroundColor = .init(named: "red_FE95B4")
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .wn_font(name: .bold, size: 18)
        btn.rx.tap.bind { [weak self] in
            self?.isRightClosure?(true)
            hidenSpringView()
        }.disposed(by: rx.disposeBag)
        btn.wn_cornerWithBorder(18)
        return btn
    }()
    
    lazy var receiveBtn: UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.backgroundColor = .init(named: "red_FE95B4")
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .wn_font(name: .bold, size: 18)
        btn.rx.tap.bind { [weak self] in
            self?.isRightClosure?(true)
            hidenSpringView()
        }.disposed(by: rx.disposeBag)
        btn.wn_cornerWithBorder(18)
        return btn
    }()
    
    lazy var inviteTF: WNTextField = {
        let tf = WNTextField()
        tf.textAlignment = .center
        tf.font = .wn_font(name: .regular, size: 32)
        tf.backgroundColor = .init(named: "white_F7F7F7")
        tf.rx.controlEvent([.editingChanged]).asObservable()
            .subscribe(onNext: { [weak self] in
                tf.text = String(tf.text?.prefix(5) ?? "")
                self?.receiveBtn.isEnabled = (tf.text?.count ?? 0) > 0
                self?.receiveBtn.backgroundColor = .init(named: (tf.text?.count ?? 0) > 0 ? "red_FE95B4" : "gray_999999")
            }).disposed(by: rx.disposeBag)
        tf.rx.controlEvent([.editingDidEndOnExit]).asObservable()
            .subscribe(onNext: { [weak self] in
                self?.isRightClosure?(true)
                hidenSpringView()
            }).disposed(by: rx.disposeBag)
        tf.wn_cornerWithBorder(4)
        tf.isHidden = true
        return tf
    }()
     
    lazy var closeBtn: UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.setImage(UIImage(named: "lib_rec_close"), for: .normal)
        btn.rx.tap.bind { [weak self] in
            self?.isRightClosure?(false)
            hidenSpringView()
        }.disposed(by: rx.disposeBag)
        btn.isHidden = true
        return btn
    }()
    
    lazy var limitedView: ReadLimitedView = {
        let view = ReadLimitedView()
        return view
    }()
    
    lazy var unlockedView: ReadUnlockedView = {
        let view = ReadUnlockedView()
        return view
    }()
    
    var limitedModel: RechargeDetailModel? {
        didSet {
            limitedView.model = limitedModel
        }
    }
    
    var unlockedModel: RechargeDetailModel? {
        didSet {
            unlockedView.model = unlockedModel
        }
    }

    var isRightClosure: BoolClosure?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .init(white: 0, alpha: 0.55)
        addSubview(bgView)
        bgView.addSubview(titleLabel)
        bgView.addSubview(descLabel)
        bgView.addSubview(limitedView)
        bgView.addSubview(unlockedView)
        bgView.addSubview(leftBtn)
        bgView.addSubview(rightBtn)
        bgView.addSubview(receiveBtn)
        bgView.addSubview(inviteTF)
        addSubview(closeBtn)
        bgView.snp.makeConstraints { (make) in
            make.top.equalTo(scaleWidth(188)+NaviTotalHeight)
            make.centerX.equalToSuperview()
            make.width.equalTo(280)
            make.height.equalTo(180)
        }
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(20)
            make.left.equalTo(12)
            make.right.equalTo(-12)
        }
        descLabel.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp.bottom).offset(8)
            make.left.equalTo(12)
            make.right.equalTo(-12)
        }
        limitedView.snp.makeConstraints { (make) in
            make.top.left.bottom.right.equalTo(0)
        }
        unlockedView.snp.makeConstraints { (make) in
            make.top.left.bottom.right.equalTo(0)
        }
        leftBtn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview().offset(-65)
            make.bottom.equalTo(-20)
            make.size.equalTo(CGSize(width: 110, height: 36))
        }
        rightBtn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview().offset(65)
            make.bottom.equalTo(-20)
            make.size.equalTo(CGSize(width: 110, height: 36))
        }
        receiveBtn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(-20)
            make.size.equalTo(CGSize(width: 110, height: 36))
        }
        inviteTF.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(receiveBtn.snp.top).offset(-20)
            make.size.equalTo(CGSize(width: 200, height: 60))
        }
        closeBtn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(bgView.snp.bottom).offset(26)
            make.size.equalTo(CGSize(width: 36, height: 36))
        }
    }
    
    func showType(_ type: SpringType, _ showStr1: String = "", _ showStr2: String = "") {
        limitedModel = nil
        limitedView.isHidden = true
        unlockedModel = nil
        unlockedView.isHidden = true
        titleLabel.text = ""
        descLabel.text = ""
        leftBtn.isHidden = false
        rightBtn.isHidden = false
        receiveBtn.isHidden = true
        inviteTF.isHidden = true
        inviteTF.text = ""
        inviteTF.resignFirstResponder()
        closeBtn.isHidden = true
        receiveBtn.backgroundColor = .init(named: "red_FE95B4")
        leftBtn.setTitle("Cancel", for: .normal)
        rightBtn.setTitle("Confirm", for: .normal)
        bgView.backgroundColor = .white
        titleLabel.textColor = .black
        descLabel.textColor = .init(named: "black_222222")
        leftBtn.backgroundColor = .init(named: "white_F3F3F3")
        leftBtn.setTitleColor(.lightGray, for: .normal)
        rightBtn.backgroundColor = .init(named: "red_FE95B4")
        rightBtn.setTitleColor(.white, for: .normal)
        receiveBtn.backgroundColor = .init(named: "red_FE95B4")
        receiveBtn.setTitleColor(.white, for: .normal)
        switch type {
        case .logout:
            titleLabel.text = "Logont"
            descLabel.text = "Are you sure to logout current account?"
        case .deleteAccount:
            titleLabel.text = "Delete Account"
            descLabel.text = "Please be careful when Delete your account"
            leftBtn.setTitle("Confirm", for: .normal)
            rightBtn.setTitle("Cancel", for: .normal)
        case .chargedOne:
            titleLabel.text = "Charged"
            descLabel.text = "Are you sure cost \(showStr2) Golds charged for \(showStr1)"
            darkModeConfig()
        case .chargedAll:
            titleLabel.text = "Charged"
            descLabel.text = "Are you sure cost \(showStr2) Golds charged for all remaining \(showStr1) chapters"
            darkModeConfig()
        case .unbindAppleId:
            titleLabel.text = "Unbind"
            descLabel.text = "Whether to unbind Apple?"
        case .chargedBook:
            titleLabel.text = "Unlock all chapters"
            descLabel.text = "Are you sure you want to spend \(showStr2) gold coins for \(showStr1)?"
            darkModeConfig()
            titleLabel.text = "Unbind"
            descLabel.text = "Whether to unbind Apple?"
        case .deleteViewedBook:
            titleLabel.text = "Delete"
            descLabel.text = "Are you sure you want to delete this book?"
            rightBtn.setTitle("Delete", for: .normal)
        case .deleteAllViewedBook:
            titleLabel.text = "Delete"
            descLabel.text = "Are you sure you want to delete all these books?"
            rightBtn.setTitle("Delete", for: .normal)
        case .guestGoldNotice:
            titleLabel.text = "Notice"
            descLabel.text = "This account is already registered, the current digital assets(golds and unlocked books) in the guest account will not be synchronized with this account."
            rightBtn.setTitle("Continue", for: .normal)
        case .clearChat:
            titleLabel.text = "Clear All"
            descLabel.text = "Are you sure you want to clear all chat record?"
            rightBtn.setTitle("Clear", for: .normal)
        case .showSmallWindow:
            titleLabel.text = "Tips"
            descLabel.text = "Do you need to keep the small window, continue reading at any time?"
            leftBtn.setTitle("Quit", for: .normal)
            rightBtn.setTitle("Confirm", for: .normal)
        case .addLibrary:
            titleLabel.text = "Add library"
            descLabel.text = "Whether to add this book to the library then exit?"
            leftBtn.setTitle("Exit", for: .normal)
            rightBtn.setTitle("Add&Exit", for: .normal)
            darkModeConfig()
        case .readingReward:
            darkModeConfig()
            leftBtn.isHidden = true
            rightBtn.isHidden = true
            receiveBtn.isHidden = false
            titleLabel.text = "Reading Reward"
            descLabel.attributedText = "Congratulations, you received a reading reward \(showStr1) Golds".wn_numberChange(.init(named: isDark() ? "yellow_FFECCE" : "red_FE6390")!, .wn_font(name: .bold, size: 18))
            receiveBtn.setTitle("Receive", for: .normal)
        case .readingLimited:
            limitedView.isHidden = false
            rightBtn.setTitle("Top Up", for: .normal)
        case .unlockedRecharge:
            unlockedView.isHidden = false
            rightBtn.setTitle("Top Up", for: .normal)
            if showStr1 == "1" {
                leftBtn.isHidden = true
                rightBtn.isHidden = true
                receiveBtn.isHidden = false
                receiveBtn.setTitle("Close", for: .normal)
                receiveBtn.backgroundColor = .init(named: "gray_999999")
            }else if showStr1 == "2" {
                leftBtn.isHidden = false
                rightBtn.isHidden = false
                receiveBtn.isHidden = true
                rightBtn.setTitle("Top Up", for: .normal)
                receiveBtn.backgroundColor = .init(named: "red_FE95B4")
            }else if showStr1 == "3" {
                leftBtn.isHidden = true
                rightBtn.isHidden = true
                receiveBtn.isHidden = false
                receiveBtn.setTitle("Purchased", for: .normal)
                receiveBtn.backgroundColor = .init(named: "gray_999999")
            }
        case .inviteCode:
            titleLabel.text = "Enter invite code"
            leftBtn.isHidden = true
            rightBtn.isHidden = true
            receiveBtn.isHidden = false
            receiveBtn.setTitle("Claim", for: .normal)
            receiveBtn.backgroundColor = .init(named: "gray_999999")
            receiveBtn.isEnabled = false
            inviteTF.isHidden = false
            closeBtn.isHidden = false
            break
        }
        layoutIfNeeded()
    }
    
    func darkModeConfig() {
        if isDark() {
            bgView.backgroundColor = .init(named: "black_121212")
            titleLabel.textColor = .init(named: "gray_777777")
            descLabel.textColor = .init(named: "gray_666666")
            leftBtn.backgroundColor = .init(named: "gray_666666")
            leftBtn.setTitleColor(.init(named: "red_D0AFB9"), for: .normal)
            rightBtn.backgroundColor = .init(named: "red_A15F73")
            rightBtn.setTitleColor(.init(named: "red_D0AFB9"), for: .normal)
            receiveBtn.backgroundColor = .init(named: "red_A15F73")
            receiveBtn.setTitleColor(.init(named: "red_D0AFB9"), for: .normal)
        }
        layoutIfNeeded()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

func showSpringType(_ type: SpringType, showStr1: String = "", showStr2: String = "") {
    if let w = appDelegate.wn_window {
        WNSpringView.shared.frame = w.frame
        WNSpringView.shared.showType(type, showStr1, showStr2)
        w.addSubview(WNSpringView.shared)
    }
}

func hidenSpringView() {
    WNSpringView.shared.removeFromSuperview()
}
